//
//  MyOrderAllOrderViewController.m
//  DPGJ
//
//  Created by ZhuoLaiQiang@Gmail.com on 11-11-19.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "MyOrderAllOrderViewController.h"
#import "Order.h"
#import "URLFactory.h"
#import <QuartzCore/QuartzCore.h>
#import "CONSTS.h"
#import "MyOrderOrderDtailViewController.h"
#import "CustomBadge.h"
#import "GoodDetailWebViewController.h"
#import "ImageButton.h"

#define SLIDER_BUTTON_ANIMATION_SECOND 0.3



@interface MyOrderAllOrderViewController()

- (void)registerAsObserver;
- (void)unregisterForChangeNotification;
- (void)requestOrderFromTaoBaoServerWithMonth:(NSInteger)months_;

- (void)viewGoodDetail:(UIButton *)sender;
- (void)didGetOrdersFormTaoBaoServer:(TaoBaoServer *)allOrderTaoBaoServer_;
- (void)failGetOrdersFormTaoBaoServer:(TaoBaoServer *)allOrderTaoBaoServer_;

- (void)buttonAnimation:(UIButton *)sender;

- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view;
- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view;
- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view;

- (IBAction)getOneMonthOrder:(UIButton *)sender;
- (IBAction)getTowMonthOrder:(UIButton *)sender;
- (IBAction)getThreeMonthOrder:(UIButton *)sender;

@end

@implementation MyOrderAllOrderViewController

@synthesize allOrderTaoBaoServer          =     _allOrderTaoBaoServer;
@synthesize tableDataSource               =     _tableDataSource;
@synthesize status                        =     _status;


#pragma mark - 系统函数
- (void)dealloc
{
    [self unregisterForChangeNotification];
    
    LF_RELEASE_SAFELY(_allOrderTaoBaoServer);
    LF_RELEASE_SAFELY(_tableDataSource);
    LF_RELEASE_SAFELY(_tableView);
    LF_RELEASE_SAFELY(_status);
    
    [_sliderButton release];
    [super dealloc];
}

- (id)initWithStatus:(NSString *)status_
{
    self = [super init];
    if (self) 
    {
        self.status = status_;
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationItem.title = @"全部订单";
    self.tableDataSource = [[[NSMutableArray alloc] init] autorelease];
    
    [self registerAsObserver];
    
    [self requestOrderFromTaoBaoServerWithMonth: 1];
}

- (void)viewDidUnload
{
    [_tableView release];
    _tableView = nil;
    [_sliderButton release];
    _sliderButton = nil;
    [super viewDidUnload];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear: animated];
    
    disSelctCell(_tableView);
}



#pragma mark - 自定义函数
- (void)viewGoodDetail:(ImageButton *)sender
{
    NSString *num_iid = sender.num_iid;
    GoodDetailWebViewController *goodDetailWebViewController = [[[GoodDetailWebViewController alloc] initWithNum_iid: num_iid] autorelease];
    
    [self.navigationController pushViewController: goodDetailWebViewController animated: YES];
}


- (void)buttonAnimation:(UIButton *)sender
{
    [_sliderButton setTitle: sender.titleLabel.text forState: UIControlStateNormal];
    [UIView beginAnimations: nil context: nil];
    [UIView setAnimationDuration: SLIDER_BUTTON_ANIMATION_SECOND];
    
    _sliderButton.center = sender.center;
    
    [UIView commitAnimations];
}

- (IBAction)getOneMonthOrder:(UIButton *)sender
{
    self.tableDataSource = [NSMutableArray array];
    
    [self buttonAnimation: sender];
    
    [self requestOrderFromTaoBaoServerWithMonth: 1];
}

- (IBAction)getTowMonthOrder:(UIButton *)sender
{
    self.tableDataSource = [NSMutableArray array];
    
    [self buttonAnimation: sender];
    
    [self requestOrderFromTaoBaoServerWithMonth: 2];
}

- (IBAction)getThreeMonthOrder:(UIButton *)sender
{
    self.tableDataSource = [NSMutableArray array];
    
    [self buttonAnimation: sender];
    
    [self requestOrderFromTaoBaoServerWithMonth: 3];
}

- (void)requestOrderFromTaoBaoServerWithMonth:(NSInteger)months_
{
    if (months_ >3)
    {
        return;
    }
    
    LF_RELEASE_SAFELY(g_start_created);
    LF_RELEASE_SAFELY(g_end_created);
    
    if (1 == months_)
    {
        int secondsOfMonth = -(60 * 60 * 24 * 30 * 3);
        NSDate *startDate = [NSDate dateWithTimeIntervalSinceNow: secondsOfMonth];
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CCT"]];
        [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
        g_start_created = [[dateFormatter stringFromDate: startDate] retain];
        ITTDINFO(@"%@", g_start_created);
        
        g_end_created = [[dateFormatter stringFromDate: [NSDate date]] retain];
        ITTDINFO(@"%@", g_end_created);
    }else if (2 == months_)
    {
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CCT"]];
        [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
        
        //设置订单的开始时间
        int secondsOfMonth = -(60 * 60 * 24 * 30 * 3);
        NSDate *startDate = [NSDate dateWithTimeIntervalSinceNow: secondsOfMonth];
        g_start_created = [[dateFormatter stringFromDate: startDate] retain];
        ITTDINFO(@"%@", g_start_created);
        
        //设置订单的结束时间
        secondsOfMonth = -(60 * 60 * 24 * 30 * 1);
        NSDate *endDate = [NSDate dateWithTimeIntervalSinceNow: secondsOfMonth];
        
        g_end_created = [[dateFormatter stringFromDate: endDate] retain];
        ITTDINFO(@"%@", g_end_created);
        
    }else if (3 == months_)
    {
        NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CCT"]];
        [dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
        
        //设置订单的开始时间
        int secondsOfMonth = -(60 * 60 * 24 * 30 * 3);
        NSDate *startDate = [NSDate dateWithTimeIntervalSinceNow: secondsOfMonth];
        g_start_created = [[dateFormatter stringFromDate: startDate] retain];
        ITTDINFO(@"%@", g_start_created);
        
        //设置订单的结束时间
        secondsOfMonth = -(60 * 60 * 24 * 30 * 2);
        NSDate *endDate = [NSDate dateWithTimeIntervalSinceNow: secondsOfMonth];
        
        g_end_created = [[dateFormatter stringFromDate: endDate] retain];
        ITTDINFO(@"%@", g_end_created);
        
    }else
    {
#ifdef DEBUG
        NSAssert(0, @"不可获取三个月前的订单");
#endif
    }
    
    LF_RELEASE_SAFELY(g_page_no);
    g_page_no = [@"1" retain];
    
    NSString *api_taobao_trades_sold_get = [URLFactory get_taobao_trades_sold_get: _status];
    
    //开始异步加载数据，然后解析数据，还要修改cell的布局，因为需要加入商品的图片
    self.allOrderTaoBaoServer = [[[TaoBaoServer alloc] initWithUrl: api_taobao_trades_sold_get 
                                                            object: self 
                                                requestIsEndSelect: @selector(didGetOrdersFormTaoBaoServer:) 
                                               requestIsFailSelect: @selector(failGetOrdersFormTaoBaoServer:) 
                                                      showWaitView: YES urlEncode: NO] autorelease];
    
    [self.allOrderTaoBaoServer startAsynchronousRequest];
}

- (void)didGetOrdersFormTaoBaoServer:(TaoBaoServer *)allOrderTaoBaoServer_
{
    
    _reloading = NO;
    [_egoRefreshTableHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading: _tableView];
    
    // NSArray *keys = [allOrderTaoBaoServer_.dic allKeys];
    ITTDINFO(@"%@", [allOrderTaoBaoServer_.dic allKeys]);
    
    //    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary: allOrderTaoBaoServer_.dic];
    //    [dic setObject: @"dd" forKey: @"error_response"];
    
    BOOL serverRetunSuccess = verifyServerRetunSuccess( allOrderTaoBaoServer_.dic );
    if (!serverRetunSuccess)
    {
        showAlert( ALERT_TITLE, ALERT_MESSAGE );
        
        return;
    }
    
#ifdef DEBUG
    writeJsonToPlist( allOrderTaoBaoServer_.dic,  taobao_trades_sold_get);
#endif
    
    NSDictionary *trades_sold_get_response = [allOrderTaoBaoServer_.dic objectForKey: @"trades_sold_get_response"];
    ITTDINFO(@"%@", [trades_sold_get_response allKeys]);
    NSDictionary *tradesDic = [trades_sold_get_response objectForKey: @"trades"];
    
    ITTDINFO(@"%@", [tradesDic allKeys]);
    
    NSArray *tradeArray = [tradesDic objectForKey: @"trade"];
    
    NSMutableArray *tempArray = [NSMutableArray array];
    
    for (NSDictionary *orderDic in tradeArray)
    {
        ITTDINFO(@"%@", orderDic);
        Order *order = [[[Order alloc] init] autorelease];
        order.total_fee = [orderDic objectForKey: @"total_fee"];
        
        order.tid = [NSString stringWithFormat: @"%@", [orderDic objectForKey: @"tid"]];//[orderDic objectForKey: @"tid"];
        ITTDINFO(@"%@", order.tid);
        
        order.created = [orderDic objectForKey: @"created"];
        NSDictionary *ordersDic = [orderDic objectForKey: @"orders"];
        NSArray *orderArray = [ordersDic objectForKey: @"order"];
        
        ITTDINFO(@"%@", orderArray);
        
        NSDictionary *orderDic1 = [orderArray objectAtIndex: 0];
        order.num = [NSString stringWithFormat: @"%@", [orderDic1 objectForKey: @"num"]];
        
        //因为官方给的图片太大，所以我找到了taoba的商品的图片的规律，只要把.jpg用jpg_sum.jpg替换就可以得到小的图片
        order.pic_path = [[orderDic1 objectForKey: @"pic_path"] stringByReplacingOccurrencesOfString: @".jpg" withString: @".jpg_sum.jpg"];
        
        
        
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////
        //因为一个订单中有可能有多个子订单，这里只取了了第一个订单，然后在图片的左上角写上有几个子订单，以此来提示用户。
        //在cell中默认只显示第一个子订单，这里就出现了一个问题，任何一个子订单的stauts都不能表明订单的状态，只有用字段“trades”中的status来表明
        //订单状态才准确
        order.status = [orderDic objectForKey: @"status"];
        //////////////////////////////////////////////////////////////////////////////////////////////////////////
        
        
        
        order.title = [orderDic1 objectForKey: @"title"];
        order.numOfBrotherOrders = [orderArray count];  //兄弟订单的个数
        
        order.num_iid = [NSString stringWithFormat: @"%@", [orderDic1 objectForKey: @"num_iid"]];

        ITTDINFO(@"%@", order.tid);
        [tempArray addObject: order];
    }
    
    [_tableDataSource addObjectsFromArray: tempArray]; //tempArray;
    self.tableDataSource = _tableDataSource;
    
    if (!(self.tableDataSource) || [self.tableDataSource count] <= 0)
    {
        showAlert(@"提示", @"该月或该账户无交易");
    }
    
    ITTDINFO(@"%@", _tableDataSource);
}

- (void)failGetOrdersFormTaoBaoServer:(TaoBaoServer *)allOrderTaoBaoServer_
{
    _reloading = NO;
    [_egoRefreshTableHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading: _tableView];
    
    showAlert(ALERT_TITLE, ALERT_MESSAGE);
}

- (void)setEGORefreshTableHeaderViewFrame
{
    if ([self.tableDataSource count] >= 5 && [self.tableDataSource count] >= ([g_page_size intValue] * [g_page_no intValue])) 
    {
        if (!_egoRefreshTableHeaderView)
        {
            _egoRefreshTableHeaderView = [[[EGORefreshTableHeaderView alloc] initWithFrame: 
                                           CGRectMake(0, _tableView.contentSize.height, 320, 100)] autorelease];
            
            _egoRefreshTableHeaderView.delegate = self;
            [_tableView addSubview: _egoRefreshTableHeaderView];
            [_egoRefreshTableHeaderView refreshLastUpdatedDate];
        }
    }
    else
    {
        [_egoRefreshTableHeaderView removeFromSuperview];
        _egoRefreshTableHeaderView = nil;
        
        return;
    }
    
    _egoRefreshTableHeaderView.frame = CGRectMake(0, _tableView.contentSize.height, 320, 100);
    
    
    ITTDINFO(@"tableView.contentSize = %@\n _egoRefreshTableHeaderView.frame = %@", \
             NSStringFromCGSize(_tableView.contentSize), NSStringFromCGRect(_egoRefreshTableHeaderView.frame));
    
}

- (void)registerAsObserver
{
    [self addObserver: self 
           forKeyPath: @"tableDataSource" 
              options: (NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) 
              context: NULL];
}

- (void)unregisterForChangeNotification
{
    [self removeObserver: self forKeyPath:@"tableDataSource"];
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.tableDataSource count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellSign = @"cellSign";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: cellSign];
    if (!cell)
    {
        NSArray *viewArray = [[NSBundle mainBundle] loadNibNamed: @"MyOrderAllOrderCell" owner: nil options: nil];
        
        for (cell in viewArray)
        {
            if ([cell.reuseIdentifier isEqualToString: cellSign])
            {
                UIButton *imageButton = (UIButton *)[cell viewWithTag: 106];
                
                cell.selectionStyle = UITableViewCellSelectionStyleGray;
                imageButton.layer.cornerRadius = 70.0;
                imageButton.layer.shadowColor = [UIColor blackColor].CGColor;
                imageButton.layer.shadowOpacity = 0.3;
                imageButton.layer.shadowOffset = CGSizeMake(4, 5);
                
                break;
            }
        }
    }
    
    NSInteger row = [indexPath row];
    Order *order = [self.tableDataSource objectAtIndex: row];
    
    NSURL *pic_url = [NSURL URLWithString: order.pic_path];
    ImageButton *imageButton = (ImageButton *)[cell viewWithTag: 106];
    [imageButton addTarget: self action: @selector(viewGoodDetail:) forControlEvents: UIControlEventTouchUpInside];
    [imageButton setImageWithURL: pic_url];
    imageButton.num_iid = order.num_iid;
    
    UILabel *titleLabel = (UILabel *)[cell viewWithTag: 101];
    titleLabel.text = order.title;
    
    UILabel *priceLabel = (UILabel *)[cell viewWithTag: 102];
    priceLabel.text = order.total_fee;
    
    UILabel *numLabel = (UILabel *)[cell viewWithTag: 103];
    numLabel.text = order.num;
    ///////////////////////////////////////////////////////////////////
    
    /*因为订单状态的字数太多，所以这里要经过简化，然后展示给用户*/
    /*
     #define  WAIT_SELLER_SEND_GOODS         @"等待卖家发货,即:买家已付款"
     #define  WAIT_BUYER_CONFIRM_GOODS       @"等待买家确认收货,即:卖家已发货"
     #define  TRADE_BUYER_SIGNED             @"买家已签收,货到付款专用"
     #define  TRADE_FINISHED                 @"交易成功"
     #define  TRADE_CLOSED                   @"付款以后用户退款成功，交易自动关闭"
     #define  TRADE_CLOSED_BY_TAOBAO         @"付款以前，卖家或买家主动关闭交易"
     */
    UILabel *statusLabel = (UILabel *)[cell viewWithTag: 107];
    statusLabel.text = getOrderStatusByStr( order.status );
    NSString *status = getOrderStatusByStr( order.status );
    if ([status isEqualToString: WAIT_SELLER_SEND_GOODS])
    {
        //#define  WAIT_SELLER_SEND_GOODS         @"等待卖家发货,即:买家已付款"
        status = @"等待卖家发货";
    }else if ([status isEqualToString: WAIT_BUYER_CONFIRM_GOODS])
    {
        //#define  WAIT_BUYER_CONFIRM_GOODS       @"等待买家确认收货,即:卖家已发货"
        status = @"等待买家确认收货";
    }else if ([status isEqualToString: WAIT_BUYER_CONFIRM_GOODS])
    {
        //#define  TRADE_CLOSED                   @"付款以后用户退款成功，交易自动关闭"
        status = @"交易已关闭";
    }else if ([status isEqualToString: TRADE_CLOSED_BY_TAOBAO])
    {
//#define  TRADE_CLOSED_BY_TAOBAO         @"付款以前，卖家或买家主动关闭交易"
        status = @"交易已关闭";
    }
    statusLabel.text = status;
    ///////////////////////////////////////////////////////////////////////////////////
    
    UILabel *timeLabel = (UILabel *)[cell viewWithTag: 104];
    timeLabel.text = order.created;
    
    if (order.numOfBrotherOrders > 1)
    {
        CustomBadge *customBadge = (CustomBadge *)[imageButton viewWithTag: 301];
        [customBadge removeFromSuperview];
        
        CustomBadge *customBadge1 = [CustomBadge customBadgeWithString:[NSString stringWithFormat: @"%d", order.numOfBrotherOrders]
                                                       withStringColor:[UIColor whiteColor] 
                                                        withInsetColor:[UIColor redColor] 
                                                        withBadgeFrame:YES 
                                                   withBadgeFrameColor:[UIColor whiteColor] 
                                                             withScale:1.0
                                                           withShining:YES];	
        customBadge1.tag = 301;
        
        CGRect rect = CGRectMake(70 - (customBadge1.frame.size.width / 2) - 3,
                                 -(customBadge1.frame.size.height / 2),
                                 customBadge1.frame.size.width, 
                                 customBadge1.frame.size.height);
        
        customBadge1.frame = rect;
        [imageButton addSubview: customBadge1];
    }else
    {
        CustomBadge *customBadge = (CustomBadge *)[imageButton viewWithTag: 301];
        [customBadge removeFromSuperview];
    }
    
    
    return cell;
}

- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    Order *order = [self.tableDataSource objectAtIndex: row];
    ITTDINFO(@"%@", order.tid);
    
    MyOrderOrderDtailViewController *myOrderOrderDtailViewController = [[[MyOrderOrderDtailViewController alloc] initWithTid: order.tid] autorelease];
    
    [self.navigationController pushViewController: myOrderOrderDtailViewController animated: YES];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{	
	[_egoRefreshTableHeaderView egoRefreshScrollViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
	
	[_egoRefreshTableHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
	
}

#pragma mark - EGORefreshTableHeaderDelegate
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view
{
    _reloading = YES;
    //刷新页码
    NSString *page_no_str = [NSString stringWithFormat: @"%d", [g_page_no intValue] + 1];
    LF_RELEASE_SAFELY(g_page_no);
    g_page_no = [page_no_str retain];
    
    //组装和获取url地址
    NSString *api_taobao_trades_sold_get = [URLFactory get_taobao_trades_sold_get: _status];
    
    //开始异步加载数据，然后解析数据，还要修改cell的布局，因为需要加入商品的图片
    self.allOrderTaoBaoServer = [[[TaoBaoServer alloc] initWithUrl: api_taobao_trades_sold_get 
                                                            object: self 
                                                requestIsEndSelect: @selector(didGetOrdersFormTaoBaoServer:) 
                                               requestIsFailSelect: @selector(failGetOrdersFormTaoBaoServer:) 
                                                      showWaitView: YES urlEncode: NO] autorelease];
    
    [self.allOrderTaoBaoServer startAsynchronousRequest];
    
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view
{
    return _reloading;
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view
{
	return [NSDate date];
}

#pragma mark - KVO
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context 
{
    [_tableView reloadData];
    
    [self setEGORefreshTableHeaderViewFrame];
}

@end
